package archsw0904.controller.shopping.order;

import java.util.Map;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.httpclient.NameValuePair;

import archsw0904.controller.shopping.common.Http;
import archsw0904.model.Book;
import archsw0904.model.OrderStatus;
import archsw0904.model.OrderedCopies;
import archsw0904.model.Orders;


/** 
 */
@Stateless
@WebService
public class ConfirmOrderBean implements ConfirmOrderBeanRemote {

	private static final String ORDER_ID_FIELD_NAME="orderId";
	private static final String TOTAL_FIELD_NAME="total";
	
	@PersistenceContext
	EntityManager em;
	
	@EJB
	OrderRollBackBeanLocal orb;
	
	@Resource
	private String deliverySystemURI;
	
	@Override
	public void setOrderPaymentStatus(Integer orderId, Boolean status) throws OrderException {
		System.out.print("PAGAMENTO " + status);
		System.out.print("ordine " + orderId);
		if(status){
			closeOrder(orderId);
		}else{
			rollbackOrder(orderId);
		}
		
	}

	private void rollbackOrder(Integer orderId) throws OrderException {
		orb.rollBackOrder(orderId);
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	private void closeOrder(Integer orderId) throws OrderException {
		
		System.out.println( "#@#@ deliverySystemURI ??? " +  deliverySystemURI );
		//ctx.get
		// Ordine esistente
		Query q = em.createQuery("SELECT OBJECT(obj) FROM Orders obj WHERE obj.id = " + orderId.toString());
		Orders order =  (Orders) q.getSingleResult();
		if ( order == null ) {
			throw new OrderException ( OrderExceptionType.OrderNotPresent ) ;
		}
		
		Map<Book,OrderedCopies> mapList = order.getBookList() ;
		
		for ( Book book : mapList.keySet() ) {
			// ripristino numero di copie available del libro
			
			// correttezza del numero di copie rilasciate
			// magazzino
			if ( book.getCopiesInStockroom().intValue() < mapList.get(book).getNumberOfCopies().intValue() ) 
				throw new OrderException ( OrderExceptionType.CopiesLT0 ) ;
					
			// aggiornamento copie nel libro
			book.setCopiesInStockroom(book.getCopiesInStockroom().intValue() - mapList.get(book).getNumberOfCopies().intValue()) ;
			
			em.persist(book) ;
			
		}
		
		order.setStatus(OrderStatus.Closed);
		
		em.persist(order) ;
		System.out.print("clode order");
		String result;
		try {
			result = Http.post(deliverySystemURI, 
						new NameValuePair(ORDER_ID_FIELD_NAME,order.getId().toString()),
						new NameValuePair(TOTAL_FIELD_NAME,order.getTotal().toString()));
			System.out.print(result);
			order.setDeliveryCode(Integer.decode(result));
			System.out.print(order.getDeliveryCode());
			em.merge(order);
		} catch (Exception e){
			 //TODO:manda una mail all'utente e agli amministratori
		}
	}
	
}
